package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "文件上传")
@Slf4j
public class CommonController {
    
    @Value("${sky.upload.base-dir:D:/sky-uploads}")
    private String uploadBaseDir;
    
    @Value("${sky.upload.access-path:/upload/**}")
    private String accessPath;

    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        // 创建上传目录（如果不存在）
        File dir = new File(uploadBaseDir);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            log.info("创建上传目录：{}，结果：{}", uploadBaseDir, created ? "成功" : "失败");
        }

        // 验证文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return Result.error("文件名无效");
        }

        // 验证文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!extension.equalsIgnoreCase(".png") && 
            !extension.equalsIgnoreCase(".jpg") && 
            !extension.equalsIgnoreCase(".jpeg")) {
            return Result.error("只支持JPG/PNG格式");
        }

        // 生成新文件名
        String newFilename = UUID.randomUUID() + extension;
        Path targetPath = Paths.get(uploadBaseDir).resolve(newFilename).normalize();

        try {
            // 保存文件
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            log.info("文件保存成功：{}", targetPath);
            
            // 返回访问URL（根据实际部署环境可能需要调整）
            String fileUrl = "http://localhost:8080/upload/" + newFilename;
            return Result.success(fileUrl);
        } catch (IOException e) {
            log.error("文件上传失败：", e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}